// 流式事件处理接口定义
import { ToolCall } from '../types';

export interface StreamEventHandlers {
  onStreamStart?: (round: number) => void;
  onContent?: (content: string) => void;
  onReasoning?: (reasoning: string) => void;
  onReasoningEnd?: () => void;
  onStreamComplete?: () => void;
  onToolCallsDetected?: (toolCalls: ToolCall[]) => void;
  onToolExecutionStart?: (toolName: string, args: any) => void;
  onToolExecutionComplete?: (toolName: string, result: string) => void;
  onToolExecutionError?: (toolName: string, error: string) => void;
  onConversationComplete?: () => void;
  onError?: (error: Error) => void;
  onDebug?: (message: string, data?: any) => void;
}

export class StreamEventEmitter {
  private handlers: StreamEventHandlers = {};

  constructor(initialHandlers?: StreamEventHandlers) {
    this.handlers = initialHandlers || {};
  }

  setHandlers(handlers: StreamEventHandlers) {
    this.handlers = { ...this.handlers, ...handlers };
  }

  updateHandlers(handlers: Partial<StreamEventHandlers>) {
    this.handlers = { ...this.handlers, ...handlers };
  }

  // 事件发射方法
  emitStreamStart(round: number) {
    this.handlers.onStreamStart?.(round);
  }

  emitContent(content: string) {
    this.handlers.onContent?.(content);
  }

  emitReasoning(reasoning: string) {
    this.handlers.onReasoning?.(reasoning);
  }

  emitReasoningEnd() {
    this.handlers.onReasoningEnd?.();
  }

  emitStreamComplete() {
    this.handlers.onStreamComplete?.();
  }

  emitToolCallsDetected(toolCalls: ToolCall[]) {
    this.handlers.onToolCallsDetected?.(toolCalls);
  }

  emitToolExecutionStart(toolName: string, args: any) {
    this.handlers.onToolExecutionStart?.(toolName, args);
  }

  emitToolExecutionComplete(toolName: string, result: string) {
    this.handlers.onToolExecutionComplete?.(toolName, result);
  }

  emitToolExecutionError(toolName: string, error: string) {
    this.handlers.onToolExecutionError?.(toolName, error);
  }

  emitConversationComplete() {
    this.handlers.onConversationComplete?.();
  }

  emitError(error: Error) {
    this.handlers.onError?.(error);
  }

  emitDebug(message: string, data?: any) {
    this.handlers.onDebug?.(message, data);
  }
}
